<template>
	<view class="container">
		<navigation-custom :config="config" :scrollTop="scrollTop" @customConduct="customConduct" :scrollMaxHeight="scrollMaxHeight" />
		<!-- <video autoplay id="goodsVideo" src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4"></video> -->
		<!-- 商品轮播图 -->
		<view class="top">
			<swiper class="goods-swiper" autoplay :duration="2000" :circular="true" indicator-dots indicator-color="#dddddd" indicator-active-color="#ff5a14">
				<swiper-item v-for="(imageUrl, index) in swiperImages" :key="index">
					<view class="swiper-item">
						<lazyLoad :src="imageUrl" class="goods-image"></lazyLoad>
						<image :src="imageUrl" class="goods-image"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<!-- 商品介绍、商品评价、商品详情 -->
		<view class="center">
			<view class="goods-detail">
				<view class="left">
					<view class="goods-name">
						{{ goods.name }}
					</view>
					<view class="goods-price">
						<!-- <text v-if="minPrice != maxPrice">¥{{ minPrice }} - ¥{{ maxPrice }}</text>
						<text v-else>¥{{ minPrice }}</text> -->
						<text>¥{{ minPrice }}</text>
					</view>
				</view>

				<view style="font-size: 28rpx; color: #999999">
					<text>销量：</text>
					<text>{{ sale }}</text>
				</view>
				<view style="font-size: 28rpx; color: #999999;margin-left: 25rpx;">
					<text>库存：</text>
					<text>{{ orderStockNum }}</text>
				</view>

				<view class="right">
					<button open-type="share">
						<text class="iconfont icon-fenxiang" style="color: #ff5a14"></text>
						<view class="goods-share">分享</view>
					</button>
				</view>
			</view>
			<!-- 规格信息弹出层 -->
<!-- 			<uni-popup ref="popup" class="popup" background-color="#fff">
				<GoodsPopup
					ref="goodsPopup"
					:popupGoods="goods"
					:specType="specType"
					:specNameList="specNameList"
					:goodsDetailList="goodsDetailList"
					:goodsStockList="goodsStockList"
					:styleList="styleList"
				></GoodsPopup>
			</uni-popup> -->
			<view class="goods-container">
				<view class="goods-spec">
					<view style="font-size: 30rpx; padding-top: 20rpx">{{ specType }}</view>
					<view class="spec-list">
						<button class="spec-item" :class="index == specActive ? 'spec-selected' : ''" v-for="(item, index) in goodsDetailList" @tap="selectSpec(index,item)" :key="index">
							{{ item.specName }}
						</button>
					</view>
				</view>
				<view class="goods-spec" v-if="kuans">
					<view style="font-size: 30rpx; padding-top: 20rpx">款式</view>
					<view class="spec-list">
						<button class="spec-item" :class="index == styleActive ? 'spec-selected' : ''" v-for="(item, index) in styleList" @tap="selectStyle(index)" :key="index">
							{{ item.styleName }}
						</button>
					</view>
				</view>
				<view class="purchase-num">
					<view>购买数量</view>
					<Counter ref="childCounter"></Counter>
				</view>
			</view>
			<!-- 商品描述 -->
			<view class="goods-desc">
				<view style="display: flex; align-items: center; padding: 15rpx 20rpx; font-size: 30rpx">
					<text class="front-bar"></text>
					<text>商品详情</text>
				</view>
				<view style="padding-bottom: 20rpx">
					<rich-text v-if="goods.goodsDesc" :nodes="goods.goodsDesc"></rich-text>
				</view>
			</view>
		</view>

		<view style="height: 100rpx">
			<!-- 正下方固定工具栏 -->
			<view class="goods-tool">
				<view class="tool-item">
					<text class="iconfont .icon-xiaoxizhongxin"></text>
					<text style="font-size: 25rpx">客服</text>
				</view>
				<view class="tool-item" @tap="gotoCart">
					<uni-badge :text="cartNum" absolute="rightTop" size="small">
						<text class="iconfont .icon-gouwuche"></text>
					</uni-badge>
					<text style="font-size: 25rpx">购物车</text>
				</view>
				<view class="common add-cart" @tap="addCart">
					<text>加入购物车</text>
				</view>
				<view class="common buy" @tap="takeOrder">
					<text>立即下单</text>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
import { getGoods, getGoodsSpecInfo,getStyleListByIds,listGoodsStock, checkCart } from '@/api/goods';
import goodsMixin from '@/mixins/goodsMixin';
import GoodsPopup from '@/components/goods_popup';
import lazyLoad from '@/components/lazyLoad.vue';
import Counter from '@/components/counter.vue';
import { mapState } from 'vuex';
export default {
	components: {
		GoodsPopup,
		lazyLoad,
		Counter
	},
	mixins: [goodsMixin],
	data() {
		return {
			config: {
				title: '商品详情'
			},
			// props
			goods: '',
			minPrice: '',
			maxPrice: '',
			specActive: 0,
			styleActive:-1,
			styleList:[],
			swiperImages:[],
			kuans:false
		};
	},
	async onLoad(params) {
		this.getGoods(params.goodsId);
		// await this.getGoodsInfo(params.goodsId);
		await this.getGoodsSpecInfo(params.goodsId);
		this.getPrice();
	},
	// onReady: function (res) {
	// 	// #ifndef MP-ALIPAY
	// 	this.videoContext = uni.createVideoContext('goodsVideo');
	// 	// #endif
	// },
	computed: {
		...mapState('goods'),
		cartNum() {
			return this.$store.getters.getCartNum(this.goods.id);
		},
		orderPrice() {
			return this.goodsDetailList.length == 0 ? 0 : this.goodsDetailList[this.specActive].goodsPrice;
		},
		sale() {
			return this.goods.initialSale + this.goods.actualSale;
		},
		orderStockNum() {
			return this.goodsStockList.length == 0 ? 0 : !this.goodsStockList[this.specActive] ? 0 : this.goodsStockList[this.specActive].stockNum;
		},
		specInfo() {
			return this.goodsDetailList.length == 0 ? 0 : this.goodsDetailList[this.specActive].specInfo;
		},
		orderSpec() {
			return this.specNameList.length == 0 ? 0 : this.specNameList[this.specActive];
		}
	},
	watch: {
	},
	methods: {
		selectSpec(goodsSpecIdx,item) {
			this.minPrice = item.goodsPrice;
			// 数组单纯赋值，vue不会触发响应式
			// this.specActive[goodsSpecIdx] = scopeIdx;
			// console.log("specActive", this.specActive)
			// 使用this.$set方法赋值数组，主动触发vue响应式
			this.specActive = goodsSpecIdx;
		},
		selectStyle(styleIdx) {
			// 数组单纯赋值，vue不会触发响应式
			// this.specActive[goodsSpecIdx] = scopeIdx;
			// console.log("specActive", this.specActive)
			// 使用this.$set方法赋值数组，主动触发vue响应式
			this.styleActive = styleIdx;
			 // 替换当前图片为特定图片  
			      this.swiperImages = [this.styleList[styleIdx].imgUrl];  
				  console.log(this.swiperImages)
			      // 清除旧定时器（如果有）  
			      if (this.replaceImageTimer) {  
			        clearTimeout(this.replaceImageTimer);  
			        this.replaceImageTimer = null;  
			      }  
			  
			      // 设置新定时器，10秒后恢复原有图片  
			      this.replaceImageTimer = setTimeout(() => {  
			        this.swiperImages = this.goods.imageList;  
			      }, 10000);  
			    
		},
		/**
		 * 获取商品信息
		 * @param {Object} goodsId
		 */
		getGoods(goodsId) {
			getGoods(goodsId)
				.then((res) => {
					this.goods = res.data;
					this.swiperImages = this.goods.imageList;
					//let splitArr = this.goods.goodsDesc.split('src="');
					//this.goods.goodsDesc = this.goods.goodsDesc.replace(/\<img/gi, '<img style="width: 100%" ').replace(/src="/gi, 'src="');
					// console.log(this.goods.goodsDesc, splitArr);
					// let goodsDesc = '';
					// for (let i = 0; i < splitArr.length; i++) {
					// 	goodsDesc += splitArr[i];
					// 	if (i % 2 === 0) {
					// 		goodsDesc += 'style="width: 100%" src="' + this.baseUrl;
					// 	}
					// }
					// this.goods.goodsDesc = goodsDesc;
					//console.log(this.goods.goodsDesc);
					
					if(this.goods.styleIds != null){
						getStyleListByIds(this.goods.styleIds).then((res) => {
							if(res.data.length > 0){
								this.kuans = true;
							}
							this.styleList = res.data
						})
					}
				})
				.catch((err) => {
					
				});
		},
		getPrice() {
			let array = this.goodsDetailList;
			//console.log(this.goodsDetailList, this.goodsStockList);
			this.minPrice = this.maxPrice = array[0].goodsPrice;
			// for (let i = 0; i < array.length; i++) {
			// 	this.minPrice = Math.min(this.minPrice, array[i].goodsPrice);
			// 	this.maxPrice = Math.max(this.maxPrice, array[i].goodsPrice);
			// }
		},
		async addCart() {
			if(this.styleActive < 0 && this.kuans){
				uni.showToast({
					title: '请选择款式',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			if (this.orderStockNum <= 0) {
				uni.showToast({
					title: '线下库存仅剩' + 0,
					icon: 'none',
					duration: 2000
				});
				this.$store.dispatch('goods/handleGoodsPopupShow', false);
				this.$refs.childCounter.purchaseNum = 1;
				return;
			}
			// 设置购物车商品
			const goodsStock = (await checkCart([this.specInfo], [this.goods.id])).data[0];
			if (this.$refs.childCounter.purchaseNum > goodsStock.stockNum) {
				uni.showToast({
					title: '线下库存仅剩' + goodsStock.stockNum,
					icon: 'none',
					duration: 2000
				});
			} else {
				let imgUrl = '';
				if(this.kuans){
					imgUrl = this.styleList[this.styleActive].imgUrl;
				}else{
					imgUrl = this.goods.thumbnail;
				}
				const { id, name, thumbnail } = this.goods;
				let goods = {
					id,
					styleInfo:this.styleList[this.styleActive],
					name,
					thumbnail:imgUrl,
					spec: this.orderSpec,
					price: this.orderPrice,
					num: this.$refs.childCounter.purchaseNum,
					specInfo: this.specInfo,
					// commission: this.commission,
					selected: true,
					isEmpty: false,
					isOffShelf: false
				};
				this.$store.dispatch('cart/addCart', goods);
			}
			
			this.$store.dispatch('goods/handleGoodsPopupShow', false);
			this.$refs.childCounter.purchaseNum = 1;
		},
		async takeOrder() {
			if(this.styleActive < 0 && this.kuans){
				uni.showToast({
					title: '请选择款式',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			if (this.orderStockNum <= 0) {
				uni.showToast({
					title: '线下库存仅剩' + 0,
					icon: 'none',
					duration: 2000
				});
				this.$store.dispatch('goods/handleGoodsPopupShow', false);
				this.$refs.childCounter.purchaseNum = 1;
				return;
			}
			const goodsStock = (await checkCart([this.specInfo], [this.goods.id])).data[0];
			if (this.$refs.childCounter.purchaseNum > goodsStock.stockNum) {
				uni.showToast({
					title: '线下库存仅剩' + goodsStock.stockNum,
					icon: 'none',
					duration: 2000
				});
			} else {
				let imgUrl = '';
				if(this.kuans){
					imgUrl = this.styleList[this.styleActive].imgUrl;
				}else{
					imgUrl = this.goods.thumbnail;
				}
				let goodsList = [
					{
						id: this.goods.id,
						styleInfo:this.styleList[this.styleActive],
						thumbnail:imgUrl,
						name: this.goods.name,
						price: this.orderPrice,
						spec: this.orderSpec,
						specInfo: this.specInfo,
						num: this.$refs.childCounter.purchaseNum
						// commission: this.commission
					}
				];
				let URLcoursePay = encodeURIComponent(JSON.stringify(goodsList))
				uni.navigateTo({
					url: `/pages/order/confirm_order?goodsList=${URLcoursePay}`
				});
			}
			this.$store.dispatch('goods/handleGoodsPopupShow', false);
			this.$refs.childCounter.purchaseNum = 1;
		},
		gotoCart() {
			uni.switchTab({
				url: '/pages/shopping_cart/shopping_cart'
			});
		}
	}
};
</script>

<style scoped lang="less">
@theme-color: #ff5a14;

// button::after {
// 	border: none;
// }

.right button {
	padding: 0;
	margin: 0;
	background-color: transparent;
	border: none;
	border-radius: 0;
	line-height: 1.5;
}
.right button::after{
	border: none;
}
.flex-row {
	display: flex;
	flex-direction: row;
}

.flex-column {
	display: flex;
	flex-direction: column;
}

.container {
	background-color: #f7f7f7;
}

.container .top {
	background-color: #fff;

	.goods-swiper,
	.swiper-item {
		height: 50vh;
	}

	.goods-swiper .goods-image {
		width: 100%;
		height: 100%;
	}
}

.container .center .goods-detail,
.goods-desc {
	background-color: #fff;
}

.container .center .goods-detail {
	display: flex;
	flex-direction: row;
	align-items: center;
	padding: 20rpx;
	.left {
		flex: 1;
		display: flex;
		flex-direction: column;
		row-gap: 30rpx;
		.goods-price {
			color: @theme-color;
			font-weight: bold;
		}
		.goods-name {
			font-size: 35rpx;
		}
	}
	.right {
		width: 100rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		row-gap: 5rpx;
		.goods-share {
			font-size: 28rpx;
			color: #999999;
		}
	}
}

.container .center .goods-desc {
	margin-top: 20rpx;
}

.goods-tool {
	width: 100%;
	height: 120rpx;
	background-color: #fff;
	display: flex;
	position: fixed;
	bottom: 0;
	padding: 20rpx 20rpx 20rpx 20rpx;
	border-top: 1px #efefef solid;
	z-index: 10;

	.tool-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		row-gap: 5rpx;
		font-size: 38rpx;
		position: relative;
	}
}

.common {
	flex: 2;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 26rpx;
	font-weight: 600;
	color: #fff;

	&.add-cart {
		background-color: #ffaa00;
		border-top-left-radius: 40rpx;
		border-bottom-left-radius: 40rpx;
	}

	&.buy {
		background-color: #eb4450;
		border-top-right-radius: 40rpx;
		border-bottom-right-radius: 40rpx;
	}
}

.front-bar {
	width: 6rpx;
	height: 32rpx;
	background-color: @theme-color;
	margin-right: 10rpx;
}
.goods-container {
	padding-left:40rpx;
	padding-right: 40rpx;
	background-color: #fff;
}
.goods-content {
	display: flex;
	flex-direction: row;

	.goods-image {
		width: 200rpx;
		height: 200rpx;
	}

	.goods-info {
		//margin-left: 30rpx;
		display: flex;
		flex-direction: column;
		gap: 8rpx;

		.order-price {
			color: @theme-color;
			font-size: 25rpx;
			font-weight: bold;
		}

		.order-spec,
		.order-stock-num {
			color: #a69999;
			font-size: 28rpx;
		}
	}
}

.goods-spec .spec-list {
	display: flex;
	flex-direction: row;
	padding-top: 20rpx;
	flex-wrap: wrap;
	gap: 20rpx;

	.spec-item {
		margin: 0;
		font-size: 24rpx;
	}

	.spec-selected {
		background-color: #ff9600;
		color: #fff;
	}
}

.purchase-num {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	padding: 40rpx 0 40rpx 0;
	font-size: 30rpx;
}

.purchase-tool {
	display: flex;
	flex-direction: row;
	height: 80rpx;

	.common {
		flex: 2;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 26rpx;
		font-weight: 600;
		color: #fff;

		&.add-cart {
			background-color: #ffaa00;
			border-top-left-radius: 40rpx;
			border-bottom-left-radius: 40rpx;
		}

		&.buy {
			background-color: #eb4450;
			border-top-right-radius: 40rpx;
			border-bottom-right-radius: 40rpx;
		}
	}
}
.goods-spec .spec-list {
	display: flex;
	flex-direction: row;
	padding-top: 20rpx;
	flex-wrap: wrap;
	gap: 20rpx;

	.spec-item {
		margin: 0;
		font-size: 24rpx;
	}

	.spec-selected {
		background-color: #ff9600;
		color: #fff;
	}
}
	.spec-selected {
		background-color: #ff9600;
		color: #fff;
	}
	.purchase-num {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		padding: 40rpx 0 40rpx 0;
		font-size: 30rpx;
	}
	
	.purchase-tool {
		display: flex;
		flex-direction: row;
		height: 80rpx;
	
		.common {
			flex: 2;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 26rpx;
			font-weight: 600;
			color: #fff;
	
			&.add-cart {
				background-color: #ffaa00;
				border-top-left-radius: 40rpx;
				border-bottom-left-radius: 40rpx;
			}
	
			&.buy {
				background-color: #eb4450;
				border-top-right-radius: 40rpx;
				border-bottom-right-radius: 40rpx;
			}
		}
	}
	/deep/ .vue-ref {
		padding-bottom: 0;
	}
</style>
